package luceneInAction.Chap01;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * @desc 读取IndexForFolder类建立起来的索引
 * @author hongxingfan
 * @since 2015年1月17日 下午3:28:47
 * @sumarize 折腾了半天，才发现还有好多包没有加进来
 */
public class SearchIndex {

	private IndexSearcher searcher;

	public SearchIndex(String indexDir) throws IOException {
		Directory dir = FSDirectory.open(new File(indexDir));
		searcher = new IndexSearcher(DirectoryReader.open(dir));
	}

	public void search(String query) throws IOException, ParseException {
		QueryParser parser = new QueryParser(Constant.TITLE, new StandardAnalyzer());
		Query q = parser.parse(query);
		long start = System.currentTimeMillis();
		TopDocs hits = searcher.search(q, 10); // 构建的查询器不好使啊
		long end = System.currentTimeMillis();
		System.out.println("Query use time:" + (end - start) + " mills, and find:" + hits.totalHits + " nums doc");
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document d = searcher.doc(scoreDoc.doc);
			StringBuilder sb = new StringBuilder();
			sb.append(d.get(Constant.TITLE)).append("-->");
			sb.append(d.get(Constant.COMPANY)).append("-->");
			sb.append(d.get(Constant.DEGREE)).append("-->");
			sb.append(d.get(Constant.JOBCLASS)).append("-->");
			sb.append(d.get(Constant.PLACE));
			System.out.println(sb.toString());
		}
	}

	public static void main(String[] args) throws IOException, ParseException {
		String indexDir = "D:/test/index";
		SearchIndex searchIndex = new SearchIndex(indexDir);
		String query = "广告销售经理";// 对title进行查询
		searchIndex.search(query);
	}
}
